<?php
/*
 * Ajax Control
 * 		1. Ajax
*/

$result = array();
$siteurl = get_option('siteurl');
$result["site_url"] = $siteurl;

if(!empty($_GET["ajax"])){
	// 0. Init
	$url = get_option('es_api_url'); 
	$url = trim($url);
	if(empty($url)){
		$result["status"] = 0;
		$result["info"] = "Error on retrieving campaign report!";
		$result["data"] = array();
		echo json_encode($result);
		unset($result);
		exit;
	}
	
	// 1. Ajax: get campaign report by id
	if(!empty($_GET["method"]) && $_GET["method"]== "report"){
		if(!empty($_GET["id"])){
			$rs = es_getCampaignReport($url, $_GET["id"]);
			if(!empty($rs)){
				$result["status"] = 1;
				$result["info"] = "Campaign report retrieved successfully!";
				$result["data"] = $rs;
			}else{
				$result["status"] = 0;
				$result["info"] = "No campaign report available!";
				$result["data"] = array();
			}
			//$result["status"] = 1;
			//$result["info"] = "Campaign report retrieved successfully!";
			//$result["data"] = array();
		}else{
			$result["status"] = 0;
			$result["info"] = "Error on retrieving campaign report!";
			$result["data"] = array();
		}
	}
	else if(0){
	}
	else{
		$result["status"] = 0;
		$result["info"] = "Unsupported ajax method.";
		$result["data"] = array();
	}
	
	echo json_encode($result);
	unset($result);
	exit;
}

/*
 * Admin Control
 * 		1. Output User Interface
 *		2. Update API link
*/

function es_option_page()
{
	$syncStatus = false;
	
	if(!empty($_POST['es_api_url'])){
		$rs = es_initServerList($_POST['es_api_url']);
		update_option('es_user_name', $rs['user_name']);
		update_option('es_list_id', $rs['list_id']);
		update_option('es_list_name', $rs['list_name']);
		update_option('es_list_size', $rs['list_size']);
		update_option('es_list_active', $rs['list_active']);
		update_option('es_list_inactive', $rs['list_inactive']);
		update_option('es_list_optout', $rs['list_optout']);
		
		if($rs['status']){
			$syncStatus = true;
		}
		update_option('es_api_url', $_POST['es_api_url']);
		
		if($syncStatus){
			?><div id="message" class="updated">Emailserving configration updated.</div><?php
		}else{
			?><div id="message" class="updated">Emailserving configration updated failed.</div><?php
		}
		$url = parse_url($_POST['es_api_url']);
		$path = $url["path"];
		if(!empty($path)){
			$key = str_replace("/api/index/soap/key/", "", $path);
			if(!empty($key)){
				update_option('es_api_key', $key);
			}
		}
	}else{
		$url = get_option('es_api_url');
		if(!empty($url)){
			$rs = es_initServerList($url);
			update_option('es_user_name', $rs['user_name']);
			update_option('es_list_id', $rs['list_id']);
			update_option('es_list_name', $rs['list_name']);
			update_option('es_list_size', $rs['list_size']);
			update_option('es_list_active', $rs['list_active']);
			update_option('es_list_inactive', $rs['list_inactive']);
			update_option('es_list_optout', $rs['list_optout']);
			
		}
	}
	
	?>
    <script>
	function ShowCampaignReport(obj, url){
		
		jQuery.get(url, function(data){
			var rs = jQuery.parseJSON(data);
			
			if(rs.status==1){
				console.log(rs);
				jQuery("#CampaignReportBox .bar h4").html('Campaign Name: '+rs.data.campName+'<a style="cursor:pointer; float:right; display:inline-block;" onclick="CloseCampaignBox()">x Close &nbsp;&nbsp;&nbsp;</a>');
				if(rs.data.campName)jQuery("#campName").html(rs.data.campName); else jQuery("#campName").html('&nbsp;');
				if(rs.data.clicked)jQuery("#clicked").html(rs.data.clicked); else jQuery("#clicked").html('&nbsp;');
				if(rs.data.creditUsed)jQuery("#creditUsed").html(rs.data.creditUsed);else jQuery("#creditUsed").html('&nbsp;');
				if(rs.data.lastActivityTime)jQuery("#lastActivityTime").html(rs.data.lastActivityTime); else jQuery("#lastActivityTime").html('&nbsp;');
				if(rs.data.finishTime)jQuery("#finishTime").html(rs.data.finishTime); else jQuery("#finishTime").html('&nbsp;');
				if(rs.data.scheduledTime)jQuery("#scheduledTime").html(rs.data.scheduledTime);else jQuery("#scheduledTime").html('&nbsp;');
				if(rs.data.startTime)jQuery("#startTime").html(rs.data.startTime); else jQuery("#startTime").html('&nbsp;');
				
				if(rs.data.opened)jQuery("#opened").html(rs.data.opened);else jQuery("#opened").html('&nbsp;');
				if(rs.data.replied)jQuery("#replied").html(rs.data.replied); else jQuery("#replied").html('&nbsp;');
				if(rs.data.totalReceived)jQuery("#totalReceived").html(rs.data.totalReceived); else jQuery("#totalReceived").html('&nbsp;');
				if(rs.data.totalRecipientsInList)jQuery("#totalRecipientsInList").html(rs.data.totalRecipientsInList); else jQuery("#totalRecipientsInList").html('&nbsp;');
				if(rs.data.totalSent)jQuery("#totalSent").html(rs.data.totalSent); else jQuery("#totalSent").html('&nbsp;');
				jQuery("#CampaignReportBox").show(5);
			}else{
				if(rs.info)
					alert("Error:"+ rs.info);
				else
					alert("Error: Unknow Error.");
			}
		});
	}
	
	function CloseCampaignBox(){
		jQuery("#CampaignReportBox").hide();
	}
	</script>
	<div class="wrap" >
        
    <div id="CampaignReportBox" style="display:none; position:">
    	<div class="bar">
        	<h4></h4>
        	
        </div>
        <div>
        	<ul>
            	<li> <span class="report_name">Campaign Name:</span> <span class="report_value" id="campName"></span> </li>
                <li> <span class="report_name">Clicked:</span> <span class="report_value" id="clicked"></span> </li>
                <li> <span class="report_name">Used Credit:</span> <span class="report_value" id="creditUsed"></span> </li>
                <li> <span class="report_name">Last Activity Time:</span> <span class="report_value" id="lastActivityTime"></span> </li>
                <li> <span class="report_name">Finish Time:</span> <span class="report_value" id="finishTime"></span> </li>
                <li> <span class="report_name">Scheduled Time:</span> <span class="report_value" id="scheduledTime"></span> </li>
                <li> <span class="report_name">Start Time:</span> <span class="report_value" id="startTime"></span> </li>
                
                <li> <span class="report_name">Opened:</span> <span class="report_value" id="opened"></span> </li>
                <li> <span class="report_name">Replied:</span> <span class="report_value" id="replied"></span> </li>
                <li> <span class="report_name">Total Received:</span> <span class="report_value" id="totalReceived"></span> </li>
                <li> <span class="report_name">Total Recipients in List:</span> <span class="report_value" id="totalRecipientsInList"></span> </li>
                <li> <span class="report_name">Total Sent:</span> <span class="report_value" id="totalSent"></span> </li>
            </ul>
        </div>
    </div>
	<?php 
		//screen_icon(); 
		$es_icon = get_option('siteurl').'/wp-content/plugins/email-serving/images/icon32.png';
	?>
    <div id="icon-emailserving-config" style="float:left;"><img src="<?php echo $es_icon; ?>" /></div>
	<h2>Emailserving Admin</h2>
	<p>Please config emailserving.</p>
    <p>&nbsp;</p>
    	<div id="es_info_table" class="email_table">
        	<table width="600">
            	<tbody>
                	<tr>
                    	<th colspan="2" align="center">
                      		<h3>
                            	Information
                                <?php $server_type = es_getUrlType($url); ?>
                                <a style="float:right;" target="_blank" class="button" href="http://member.emailserving.<?php echo $server_type; ?>/member/campaign/selectlist/selected/<?php echo get_option('es_list_id');   ?>">Create New Campaign</a>
                            </h3>
                        </th>
                    </tr>
                    
                    <tr>
                    	<td class="first">User name: </td>
                        <td>
                        	<?php
								$userName = get_option('es_user_name');
								echo $userName;
							?>
                        </td>
                    </tr>
                    <tr>
                    	<td class="first">List Id: </td>
                        <td>
                        	<?php
								$listId = get_option('es_list_id');
								echo $listId;
							?>
                        </td>
                    </tr>
                    <tr>
                    	<td class="first">List Name: </td>
                        <td>
                        	<?php
								$listName = get_option('es_list_name');
								echo $listName;
							?>
                        </td>
                    </tr>
                    <tr>
                    	<td class="first">List Size: </td>
                        <td>
                        	<?php
								$listSize = get_option('es_list_size');
								echo $listSize;
							?>
                        </td>
                    </tr>
                    <tr>
                    	<td class="first">List active: </td>
                        <td>
                        	<?php
								$listActive = get_option('es_list_active');
								echo $listActive;
							?>
                        </td>
                    </tr>
                    <tr>
                    	<td class="first">List inactive: </td>
                        <td>
                        	<?php
								$listInactive = get_option('es_list_inactive');
								echo $listInactive;
							?>
                        </td>
                    </tr>
                    <tr>
                    	<td  class="first">List option out: </td>
                        <td>
                        	<?php
								$listOptout = get_option('es_list_optout');
								echo $listOptout;
							?>
                        </td>
                    </tr>
                    <tr>
                    	<td class="first">Sync Url: </td>
                        <td>
                        	<?php
                            	$es_sync_url = es_getSyncUrl();
								if(!empty($es_sync_url))
									echo "<a href='$es_sync_url'>" . $es_sync_url . "</a>";
								else
									echo "N/A";
							?>
                            <br />(emailserving use this url call wordpress. )
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
        
        <p>&nbsp;</p>
            <div id="es_info_table" class="email_table">
                <table width="600">
                    <tbody>
                        <tr>
                            <th colspan="2">
                                <h3>Campaigns</h3>
                            </th>
                        </tr>
                        <tr>
                        	<td>Campain Name</td>
                            <td>Schedule Time</td>
                            <td>Update Time</td>
                            <td>Status</td>
                            <td>Report</td>
                        </tr>
                        <?php 
						foreach($rs["campainies"] as $key => $value){ 
							
						?>
                                <tr>
                                    <td> <?php echo $value["name"]; ?> </td>
                                    <td> <?php if(!empty($value["schedule_time"]))echo date("Y-m-d H:i:s", $value["schedule_time"]);?></td>
                                    <td> <?php if(!empty($value["update_time"])) echo date("Y-m-d H:i:s", $value["update_time"]); ?></td>
                                    <td> <?php echo $value["status"]; ?></td>
                                    <td>
                                    	<?php if($value["status"] == "finished"){ ?>
                                        <a target="_blank" class="button" style="cursor:pointer;" onclick="ShowCampaignReport(this,'<?php echo get_option('siteurl'); ?>/wp-admin/admin.php?page=emailserving-config&ajax=ajax&method=report&id=<?php echo $value["id"]; ?>');">report</a>
                                        <?php } ?>
                                    </td>
                                </tr>
                        <?php 
						} 
						?>
                    </tbody>
                </table>
        
        <p>&nbsp;</p>
        
        <?php 
			$api_url = get_option('es_api_url');
			$urlDisplay =  "";
			$urlDisplay = empty($api_url)?"display:bolck;":"display:none;";
		?>
        
        <div id="es_config_table" class="email_table">
        	<form action="" method="post">
            <div><a class="button configration_toggle" onclick="jQuery('#config_table').toggle()">API Configration</a></div>
        	<table id="config_table" width="600" style="<?php echo $urlDisplay; ?>">
            	<tbody>
                	<tr>
                    	<th colspan="2">
                        	<h3>Configration</h3>
                        </th>
                        
                    </tr>
                	<tr>
                    	<td  class="first">API URL: </td>
                        <td><input name="es_api_url" value="<?php echo get_option('es_api_url'); ?>" size="100" /></td>
                    </tr>
                 
                    <tr>
                    	<td  class="first"></td>
                        <td>
                     
                        <p class="submit" style="padding:0; "><input type="submit" value="Update/Refresh" class="button-primary"  /></p>
                        
                        </td>
                    </tr>
                </tbody>
            </table>
            </form>
        </div>
	</div>
	<?php
}

function es_plugin_menu()
{
	add_menu_page('Emailserving Settings','Emailserving', 'manage_options', 'emailserving-config', 'es_option_page',
				 get_option('siteurl').'/wp-content/plugins/email-serving/images/icon.png');
}

add_action('admin_menu', 'es_plugin_menu');







